package xu.zhi.qing.share.service;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xu.zhi.qing.collect.entity.Collect;
import xu.zhi.qing.common.constant.Configuration;
import xu.zhi.qing.share.dao.ShareDao;
import xu.zhi.qing.share.entity.ShareCondition;
import xu.zhi.qing.common.service.BaseService;
import xu.zhi.qing.exception.HideShareException;
import xu.zhi.qing.exception.ShowShareException;
import xu.zhi.qing.praise.entity.Like;
import xu.zhi.qing.share.entity.Share;
import xu.zhi.qing.share.entity.ShareImg;
import xu.zhi.qing.share.vo.ShareImgVo;
import xu.zhi.qing.share.vo.SharePageVo;
import xu.zhi.qing.share.vo.ShareVo;
import xu.zhi.qing.user.entity.User;

import java.text.SimpleDateFormat;
import java.util.*;

@Transactional
@Service
public class ShareService extends BaseService<Share> {
    //格式化日期
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");

    private ShareVo createShareVo(Share share, Integer currentUserId) {

        ShareVo shareVo = new ShareVo();
        BeanUtils.copyProperties(share,shareVo);
        shareVo.setCreateTime(sdf.format(share.getCreateTime()));
        shareVo.setCollectCount(collectDao.countByShareId(share.getId()));
        shareVo.setLikeCount(likeDao.countByShareId(share.getId()));
        shareVo.setCommentCount(commentDao.countByShareId(share.getId()));
        User user = userDao.findById(share.getUserId());
        shareVo.setUserId(user.getId());
        shareVo.setUserName(user.getUsername());
        shareVo.setUserImg(user.getImgPath());
        //当前用户是否点赞过
        for (Like like : likeDao.findByShareId(share.getId())) {
            if (like.getUserId().equals(currentUserId)) {
                shareVo.setLike(true);
                break;
            }
        }
        //当前用户是否收藏过
        for (Collect collect : collectDao.findByShareId(share.getId())) {
            if (collect.getUserId().equals(currentUserId)) {
                shareVo.setCollect(true);
                break;
            }
        }
        //分享图片集合
        List<ShareImgVo> shareImgs = new ArrayList<>();
        List<ShareImg> list = shareImgDao.findByShareId(share.getId());
        for (ShareImg shareImg : list) {
            ShareImgVo shareImgVo = new ShareImgVo();
            shareImgVo.setBigPath(shareImg.getImgPath());
            shareImgVo.setSmallPath(shareImg.getSmallImgPath());
            shareImgs.add(shareImgVo);
        }
        shareVo.setShareImgs(shareImgs);
        return shareVo;
    }
    //封装分页数据
    private void createPageInfo(SharePageVo sharePageVo) {
        //分页数据
        Integer count = sharePageVo.getTotalCount();
        Integer rows = sharePageVo.getPageSize();
        Integer page = sharePageVo.getPageNo();
        Integer pageCount = count%rows==0?count/rows:count/rows+1;
        Integer nextPage = page==pageCount?page:page+1;
        Integer prePage = page==1?page:page-1;
        sharePageVo.setPageCount(pageCount);
        sharePageVo.setNextPage(nextPage);
        sharePageVo.setPrePage(prePage);
    }

    public SharePageVo findByPage(ShareCondition shareCondition) {
        //目标分页
        SharePageVo sharePageVo = new SharePageVo();
        //目标List
        List<ShareVo> shareVos = new ArrayList<>();
        //条件集合
        Map<String,Object> params = new HashMap<>();
        //条件：用户id
        if (shareCondition.getUserId() != null) {
            params.put("userId",shareCondition.getUserId());
        }
        //条件：分享内容含有condition字符串
        if (shareCondition.getCondition() != null && !"".equals(shareCondition.getCondition())) {
            params.put("content","%"+shareCondition.getCondition()+"%");
        }
        //条件：不传userId和condition->显示主页（显示当前用户的分享以及当前用户所关注的人的分享）
        if (shareCondition.getUserId() == null && (shareCondition.getCondition() == null || "".equals(shareCondition.getCondition())) && shareCondition.getCurrentUserId() != null) {
            params.put("userId",shareCondition.getCurrentUserId());
            params.put("fansId",shareCondition.getCurrentUserId());
        }
        // 条件：公开分享，用户没有被屏蔽，或我的(隐私)分享
        if (shareCondition.getCurrentUserId() != null) {
            params.put("id",shareCondition.getCurrentUserId());
        }
        //根据时间倒序排序
        params.put("page",shareCondition.getPageNo());
        params.put("rows",shareCondition.getPageSize());

        sharePageVo.setPageNo(shareCondition.getPageNo());
        sharePageVo.setPageSize(shareCondition.getPageSize());
        sharePageVo.setTotalCount(shareDao.countByMap(params));
        //当前登录用户的id
        Integer currentUserId = shareCondition.getCurrentUserId();
        for (Share share : shareDao.findPagination(params)) {
            shareVos.add(createShareVo(share,currentUserId));
        }
        sharePageVo.setItems(shareVos);
        createPageInfo(sharePageVo);
        return sharePageVo;
    }

    public SharePageVo findByLikeAndPage(ShareCondition shareCondition) {
        //目标分页
        SharePageVo sharePageVo = new SharePageVo();
        //目标List
        List<ShareVo> shareVos = new ArrayList<>();
        //条件集合
        Map<String,Object> params = new HashMap<>();
        //条件：用户id
        if (shareCondition.getUserId() != null) {
            params.put("userId",shareCondition.getUserId());
        }
        //条件：公开分享，用户没有被屏蔽，或我的(隐私)分享
        if (shareCondition.getCurrentUserId() != null) {
            params.put("id",shareCondition.getCurrentUserId());
        }
        params.put("page",shareCondition.getPageNo()<1?0:shareCondition.getPageNo()-1);
        params.put("rows",shareCondition.getPageSize());

        sharePageVo.setPageNo(shareCondition.getPageNo());
        sharePageVo.setPageSize(shareCondition.getPageSize());
        sharePageVo.setTotalCount(likeDao.countByPage(params));
        //当前登录用户的id
        Integer currentUserId = shareCondition.getCurrentUserId();
        List<Like> likeList = likeDao.findByPage(params);
        for (Like like : likeList) {
            Share share = shareDao.get(like.getShareId());
            shareVos.add(createShareVo(share,currentUserId));
        }
        sharePageVo.setItems(shareVos);
        createPageInfo(sharePageVo);
        return sharePageVo;
    }

    public SharePageVo findByCommentAndPage(ShareCondition shareCondition) {
        //目标分页
        SharePageVo sharePageVo = new SharePageVo();
        //目标List
        List<ShareVo> shareVos = new ArrayList<>();
        //条件集合
        Map<String,Object> params = new HashMap<>();
        //条件：用户id
        if (shareCondition.getUserId() != null) {
            params.put("userId",shareCondition.getUserId());
        }
        //条件：公开分享，用户没有被屏蔽，或我的(隐私)分享
        if (shareCondition.getCurrentUserId() != null) {
            params.put("id",shareCondition.getCurrentUserId());
        }
        //根据时间倒序排序
        params.put("page",shareCondition.getPageNo()<1?0:shareCondition.getPageNo()-1);
        params.put("rows",shareCondition.getPageSize());

        sharePageVo.setPageNo(shareCondition.getPageNo());
        sharePageVo.setPageSize(shareCondition.getPageSize());
        sharePageVo.setTotalCount(commentDao.countCommentByPage(params));

        for (Map<String,Object> share : commentDao.findCommentByPage(params)) {
            ShareVo shareVo = new ShareVo();
            shareVo.setId((Integer) share.get("id"));
            shareVo.setContent((String) share.get("content"));
            shareVo.setCreateTime(sdf.format(share.get("create_time")));
            shareVo.setStatus((Integer) share.get("status"));
            shareVo.setUserId((Integer) share.get("user_id"));
            shareVo.setUserName((String) share.get("username"));
            shareVo.setUserImg((String) share.get("img_path"));
            shareVo.setCollectCount(commentDao.collectCount((Integer) share.get("id")));
            shareVo.setLikeCount(commentDao.likeCount((Integer) share.get("id")));
            shareVo.setCommentCount(commentDao.commentCount((Integer) share.get("id")));
            //当前用户是否点赞过
            int likeCount = likeDao.countByShareIdAndUserId((Integer) share.get("id"),shareCondition.getCurrentUserId());
            if (likeCount > 0) {
                shareVo.setLike(true);
            }
            //当前用户是否收藏过
            int collectCount = collectDao.countByShareIdAndUserId((Integer) share.get("id"),shareCondition.getCurrentUserId());
            if (collectCount>0){
                shareVo.setCollect(true);
            }
            //分享图片集合
            List<ShareImgVo> shareImgs = new ArrayList<>();
            List<ShareImg> shareImgList = shareImgDao.findByShareId((Integer) share.get("id"));
            for (ShareImg shareImg : shareImgList) {
                ShareImgVo shareImgVo = new ShareImgVo();
                //原图
                shareImgVo.setBigPath(shareImg.getImgPath());
                //缩略图
                shareImgVo.setSmallPath(shareImg.getSmallImgPath());
                shareImgs.add(shareImgVo);
            }
            shareVo.setShareImgs(shareImgs);
            shareVos.add(shareVo);
        }
        sharePageVo.setItems(shareVos);
        createPageInfo(sharePageVo);
        return sharePageVo;
    }

    public SharePageVo findByCollectAndPage(ShareCondition shareCondition) {
        //目标分页
        SharePageVo sharePageVo = new SharePageVo();
        //目标List
        List<ShareVo> shareVos = new ArrayList<>();
        //条件集合
        Map<String,Object> params = new HashMap<>();
        //条件：用户id
        if (shareCondition.getUserId() != null) {
            params.put("userId",shareCondition.getUserId());
        }
        // 条件：公开分享，用户没有被屏蔽，或我的(隐私)分享
        if (shareCondition.getCurrentUserId() != null) {
            params.put("id",shareCondition.getCurrentUserId());
        }
        //根据时间倒序排序
        params.put("page",shareCondition.getPageNo()<1?0:shareCondition.getPageNo()-1);
        params.put("rows",shareCondition.getPageSize());

        sharePageVo.setPageNo(shareCondition.getPageNo());
        sharePageVo.setPageSize(shareCondition.getPageSize());
        Integer size = collectDao.countByPage(params);
        sharePageVo.setTotalCount(size);
        //当前登录用户的id
        Integer currentUserId = shareCondition.getCurrentUserId();
        for (Collect collect : collectDao.findByPage(params)) {
            Share share = shareDao.get(collect.getShareId());
            shareVos.add(createShareVo(share,currentUserId));
        }
        sharePageVo.setItems(shareVos);
        createPageInfo(sharePageVo);
        return sharePageVo;
    }

    public SharePageVo findByLikeRankingAndPage(ShareCondition shareCondition) {
        //目标分页
        SharePageVo sharePageVo = new SharePageVo();
        //目标List
        List<ShareVo> shareVos = new ArrayList<>();
        //条件集合
        Map<String,Object> params = new HashMap<>();

        //条件：时间筛选（全部，今天，最近一周）
        if (shareCondition.getLastNDays() != null) {
            Calendar calendar = Calendar.getInstance();
            //前N天
            calendar.add(Calendar.DATE, 1 - shareCondition.getLastNDays());
            //设置时分秒为0
            calendar.set(Calendar.AM_PM, Calendar.AM);
            calendar.set(Calendar.HOUR,0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            params.put("createTime",calendar.getTime());
        }
        //根据时间倒序排序
        params.put("page",shareCondition.getPageNo()<1?0:shareCondition.getPageNo()-1);
        params.put("rows",shareCondition.getPageSize());
        sharePageVo.setPageNo(shareCondition.getPageNo());
        sharePageVo.setPageSize(shareCondition.getPageSize());
        sharePageVo.setTotalCount(shareDao.countByLikeRankingAndPage(params));
        //当前登录用户的id
        Integer currentUserId = shareCondition.getCurrentUserId();
        for (Share share : shareDao.findByLikeRankingAndPage(params)) {
            shareVos.add(createShareVo(share,currentUserId));
        }
        sharePageVo.setItems(shareVos);
        createPageInfo(sharePageVo);
        return sharePageVo;
    }

    public void deleteShare(Share share) {
        Share tShare = shareDao.get(share.getId());
        //需要先把关联依赖的数据删掉
        // likes
        likeDao.deleteByShareId(share.getId());
        // shareImgs
        shareImgDao.deleteByShareId(share.getId());
        // comments
        commentDao.deleteByShareId(share.getId());
        // collects
        collectDao.deleteByShareId(share.getId());

        shareDao.delete(tShare);
    }

    @Transactional(rollbackFor = Exception.class)
    public void hideShare(Integer currentUserId, Integer shareId) throws HideShareException {
        User currentUser = userDao.get(currentUserId);
        Share share = shareDao.get(shareId);
        if (!currentUser.getId().equals(share.getUserId())) {
            throw new HideShareException("你没有权限屏蔽这条分享！");
        }
        share.setStatus(Share.STATUS_PRIVATE);
    }

    @Transactional(rollbackFor = Exception.class)
    public void showShare(Integer currentUserId, Integer shareId) throws ShowShareException {
        User currentUser = userDao.get(currentUserId);
        Share share = shareDao.get(shareId);
        if (!currentUser.getId().equals(share.getUserId())) {
            throw new ShowShareException("你没有权限取消这条分享的屏蔽状态！");
        }
        share.setStatus(Share.STATUS_PUBLIC);
    }
}
